package org.example.project.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import lombok.RequiredArgsConstructor;
import org.example.project.common.convention.result.Result;
import org.example.project.common.convention.result.Results;
import org.example.project.dto.req.ShortLinkCreatReqDTO;
import org.example.project.dto.req.ShortLinkPageReqDTO;
import org.example.project.dto.req.ShortLinkUpdateReqDTO;
import org.example.project.dto.resp.GroupShortLinkCountRespDTO;
import org.example.project.dto.resp.ShortLinkCreateRespDTO;
import org.example.project.dto.resp.ShortLinkPageRespDTO;
import org.example.project.handler.CustomBlockHandler;
import org.example.project.service.ShortLinkService;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * 短链接控制器
 *
 * @author weibin
 * @since 2025/10/5 0:12
 */
@RestController
@RequiredArgsConstructor
public class ShortLinkController {

    private final ShortLinkService shortLinkService;

    @GetMapping("/{shortUri}")
    public void routerShortUri(@PathVariable("shortUri") String shortUri, ServletRequest request, ServletResponse response) throws IOException {
        /*
        获取到完整短链接，取到其对应的完整原始链接，进行302跳转，所以这里直接操作的是response，不需要有返回值
        301:永久重定向
        302：临时重定向
        我们得选择302，让每次访问短链接都去访问后端服务进行替换，因为我们需要监控这个过程，否则你选择301那浏览器那直接帮你跳转了
         */
        shortLinkService.routerShortUri(shortUri, request, response);
    }

    @PostMapping("/short-link/createShortLink")
    @SentinelResource(
            value = "create_short_link",
            blockHandler = "createShortLinkBlockHandlerMethod",
            blockHandlerClass = CustomBlockHandler.class
    )
    public Result<ShortLinkCreateRespDTO> createShortLink(@RequestBody ShortLinkCreatReqDTO requestParam) {
        return Results.success(shortLinkService.createShortLink(requestParam));
    }

    @PostMapping("/short-link/updateShortLink")
    public Result<Void> updateShortLink(@RequestBody ShortLinkUpdateReqDTO requestParam) {
        shortLinkService.updateShortLink(requestParam);
        return Results.success();
    }

    @PostMapping("/short-link/pageShortLink")
    public Result<IPage<ShortLinkPageRespDTO>> pageShortLink(@RequestBody ShortLinkPageReqDTO requestParam) {
        return Results.success(shortLinkService.pageShortLink(requestParam));
    }

    @GetMapping("/short-link/listGroupShortLinkCount")
    public Result<List<GroupShortLinkCountRespDTO>> listGroupShortLinkCount(@RequestParam("requestParam") List<String> requestParam) {
        return Results.success(shortLinkService.listGroupShortLinkCount(requestParam));
    }


}
